package whr.modules.ask.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
//import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.ParseException;
import net.sf.jsqlparser.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import whr.common.utils.PageUtils;
import whr.common.utils.Query;

import whr.modules.ask.dao.SalaryDao;
import whr.modules.ask.entity.ReplyEntity;
import whr.modules.ask.entity.SalaryEntity;
import whr.modules.ask.service.SalaryService;
import whr.modules.sys.entity.SysUserEntity;
import whr.modules.sys.service.SysUserService;


@Service("salaryService")
public class SalaryServiceImpl extends ServiceImpl<SalaryDao, SalaryEntity> implements SalaryService {
    @Autowired
    private SalaryService salaryService;
    @Autowired
    private SalaryDao salaryDao;
    @Autowired
    private SysUserService sysUserService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        // 获取前端传来的名字参数
        String realName = (String) params.get("key");
        QueryWrapper<SysUserEntity> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq(StringUtils.isNotBlank(realName), "real_name", realName);
        List<SysUserEntity> userList = sysUserService.list(userQueryWrapper);

        // 获取前端传来的日期参数
        String dateStr = (String) params.get("selectDate");

        IPage<SalaryEntity> page;
        QueryWrapper<SalaryEntity> queryWrapper = new QueryWrapper<>();

        // 处理用户筛选
        if (CollectionUtils.isNotEmpty(userList)) {
            List<Long> userIds = userList.stream().map(SysUserEntity::getUserId).collect(Collectors.toList());
            queryWrapper.in("user_id", userIds);
        }

        // 处理日期筛选
        if (StringUtils.isNotEmpty(dateStr)) {
            try {
                // 解析前端传来的日期
                Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);

                // 获取年份和月份
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH) + 1;

                // 构建当月第一天和最后一天的日期
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                Date firstDay = calendar.getTime();

                calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
                Date lastDay = calendar.getTime();

                // 查询当月的所有记录
                queryWrapper.between("salary_time", firstDay, lastDay);
            } catch (java.text.ParseException e) {
                throw new RuntimeException(e);
            }
        }

        // 执行分页查询
        page = this.page(new Query<SalaryEntity>().getPage(params), queryWrapper);

        // 关联用户姓名
        List<SalaryEntity> salaryEntities = page.getRecords();
        if (CollectionUtils.isNotEmpty(salaryEntities)) {
            // 批量查询用户信息，减少数据库交互
            Map<Long, SysUserEntity> userMap = new HashMap<>();
            Set<Long> userIds = salaryEntities.stream()
                    .map(SalaryEntity::getUserId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet());

            if (CollectionUtils.isNotEmpty(userIds)) {
                QueryWrapper<SysUserEntity> userWrapper = new QueryWrapper<>();
                userWrapper.in("user_id", userIds);
                sysUserService.list(userWrapper).forEach(user -> userMap.put(user.getUserId(), user));
            }

            // 设置用户姓名
            for (SalaryEntity salary : salaryEntities) {
                SysUserEntity user = userMap.get(salary.getUserId());
                if (user != null) {
                    salary.setRealName(user.getRealName());
                }
            }
        }

        return new PageUtils(page);
    }


}

